package com.ruoyi.travel.service.impl;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.travel.domain.TravelItinerary;
import com.ruoyi.travel.domain.TravelItineraryContent;
import com.ruoyi.travel.mapper.TravelItineraryMapper;
import com.ruoyi.travel.mapper.TravelItineraryContentMapper;
import com.ruoyi.travel.service.ITravelItineraryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;

@Service
public class TravelItineraryServiceImpl implements ITravelItineraryService {

    @Autowired
    private TravelItineraryMapper itineraryMapper;

    @Autowired
    private TravelItineraryContentMapper contentMapper;

    @Override
    public List<TravelItinerary> selectTravelItineraryList(TravelItinerary itinerary) {
        return itineraryMapper.selectTravelItineraryList(itinerary);
    }

    @Override
    public TravelItinerary selectTravelItineraryByItineraryId(Long itineraryId) {
        return itineraryMapper.selectTravelItineraryByItineraryId(itineraryId);
    }

    @Override
    public TravelItinerary selectTravelItineraryWithContent(Long itineraryId) {
        // 1. 查询主行程
        TravelItinerary itinerary = itineraryMapper.selectTravelItineraryByItineraryId(itineraryId);
        if (itinerary == null) {
            return null;
        }
        // 2. 查询关联内容
        List<TravelItineraryContent> contents = contentMapper.selectByItineraryId(itineraryId);
        itinerary.setItineraryContents(contents); // 修正：与实体类setter匹配
        return itinerary;
    }

    @Override
    @Transactional
    public int insertTravelItinerary(TravelItinerary itinerary) {
        // 1. 保存主行程（自动填充ID）
        itinerary.setCreateTime(DateUtils.getNowDate());
        int rows = itineraryMapper.insertTravelItinerary(itinerary);
        if (rows <= 0) {
            return 0;
        }

        // 2. 保存关联内容（关键：使用实体类正确字段名）
//        List<TravelItineraryContent> contents = itinerary.getItineraryContents();
//        if (contents != null && !contents.isEmpty()) {
//            for (TravelItineraryContent content : contents) {
//                content.setItineraryId(itinerary.getItineraryId()); // 关联行程ID
//            }
//            contentMapper.batchInsert(contents); // 批量插入
//        }
        return rows;
    }

    @Override
    @Transactional
    public int updateTravelItinerary(TravelItinerary itinerary) {
        itinerary.setUpdateTime(DateUtils.getNowDate());
        return itineraryMapper.updateTravelItinerary(itinerary);
    }

    @Override
    @Transactional
    public int deleteTravelItineraryByItineraryIds(Long[] itineraryIds) {
        // 1. 先删除关联内容
        for (Long id : itineraryIds) {
            contentMapper.deleteByItineraryId(id);
        }
        // 2. 再删除主表（逻辑删除）
        return itineraryMapper.deleteTravelItineraryByItineraryIds(itineraryIds);
    }
}
